<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Services\UserService;

/**
 * 后台用户管理控制器
 * 
 * 职责：
 * - 处理后台用户管理相关的HTTP请求
 * - 调用服务层处理业务逻辑
 * - 统一响应格式
 */
class UserController extends Controller
{
    /**
     * 用户服务
     * 
     * @var UserService
     */
    protected UserService $userService;

    /**
     * 构造器
     */
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    /**
     * 显示用户列表
     * 
     * @param Request $request
     * @return \Inertia\Response
     */
    public function index(Request $request)
    {
        // 获取过滤条件
        $filters = $request->only([
            'search',
            'sort'
        ]);

        // 调用服务层获取用户列表
        $users = $this->userService->getUsers($filters, 10);

        // 获取统计数据
        $stats = $this->userService->getStats();

        return Inertia::render('Admin/Users/Index', [
            'users' => [
                'data' => $users->map(function ($user) {
                    return [
                        'id' => $user->id,
                        'name' => $user->name,
                        'email' => $user->email,
                        'email_verified_at' => $user->email_verified_at,
                        'created_at' => $user->created_at,
                        'posts_count' => $user->posts_count ?? 0,
                        'comments_count' => $user->comments_count ?? 0,
                    ];
                }),
                'meta' => [
                    'current_page' => $users->currentPage(),
                    'from' => $users->firstItem(),
                    'last_page' => $users->lastPage(),
                    'links' => $users->linkCollection()->toArray(),
                    'path' => $users->path(),
                    'per_page' => $users->perPage(),
                    'to' => $users->lastItem(),
                    'total' => $users->total(),
                ],
            ],
            'filters' => $filters,
            'stats' => $stats,
        ]);
    }

    /**
     * 显示创建用户表单
     * 
     * @return \Inertia\Response
     */
    public function create()
    {
        return Inertia::render('Admin/Users/Create');
    }

    /**
     * 创建新用户
     * 
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        try {
            // 调用服务层创建用户
            $this->userService->create($validated);

            return redirect()
                ->route('admin.users.index')
                ->with('success', '用户创建成功！');
        } catch (\Exception $e) {
            return back()
                ->withInput()
                ->with('error', '创建失败：' . $e->getMessage());
        }
    }

    /**
     * 显示用户详情
     * 
     * @param User $user
     * @return \Inertia\Response
     */
    public function show(User $user)
    {
        // 调用服务层获取用户详情
        $userData = $this->userService->getUserDetail($user);

        return Inertia::render('Admin/Users/Show', [
            'user' => $userData,
        ]);
    }

    /**
     * 显示编辑用户表单
     * 
     * @param User $user
     * @return \Inertia\Response
     */
    public function edit(User $user)
    {
        return Inertia::render('Admin/Users/Edit', [
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'email_verified_at' => $user->email_verified_at,
            ],
        ]);
    }

    /**
     * 更新用户
     * 
     * @param Request $request
     * @param User $user
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, User $user)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:8|confirmed',
        ]);

        try {
            // 调用服务层更新用户
            $this->userService->update($user, $validated);

            return redirect()
                ->route('admin.users.index')
                ->with('success', '用户更新成功！');
        } catch (\Exception $e) {
            return back()
                ->withInput()
                ->with('error', '更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除用户
     * 
     * @param User $user
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(User $user)
    {
        try {
            // 调用服务层删除用户
            $this->userService->delete($user);

            return redirect()
                ->route('admin.users.index')
                ->with('success', '用户删除成功！');
        } catch (\Exception $e) {
            return back()
                ->with('error', '删除失败：' . $e->getMessage());
        }
    }
}
